import { defineStore, acceptHMRUpdate } from 'pinia'
import { createSiteToServer, saveSiteDatasToServer } from '@/service/web/pages'
import { onlineSite as online } from '@/service/web/user'
import { getSiteDataToServer, getTempPreviewUrl, recoverSiteQrcode } from '@/service/web/user'
import { useRouter } from 'vue-router'
import router from '@/router';
import { CardSiteDataDefault, BUSINESS_NO_CARD } from '@/views/card/js/data/cardSiteData';



declare interface IWebCardComp {
  siteData: any,
  sitePreshowData: any,
  curTarget: any,
  mgSitePreview: any,
  curPage: any,
  curPageData: any,
  curLayoutType: any
}

export const useWebCardCompStore = defineStore('webCardComp', {
  state: (): IWebCardComp => {
    return {
      siteData: {  // card site data
        id: '',
        attrs: {  // pageInfo
          // ..._.cloneDeep(CardSiteDataDefault.attrs),
          desc: '',
        },
        pages: [],
        controls: [],  // cardLists
        uids: [],  // 统计 cardLists 所有相关 uids
        mids: [],  // 统计 cardLists 所有相关 mids
      },
      sitePreshowData: {  // card site preShow data
        status: '',
        // pageurl: '',  // 站点链接
        // qrcode: '',  // 站点链接的二维码
        // update_time: '',  // 更新时间
      },
      curTarget: {  // 当前编辑 item; ⚠️注意：仅暂存 itemId 以及 parentId
        itemId: '',
        parentId: '',
      },
      mgSitePreview: {  // 站点预览配置
        isActive: false,  // show / hide
      },
      curPage: 0,  // 当前页 pages[0]
      curPageData: [],  // 当前页 data
      curLayoutType: 'PAGE',  // PAGE / PANEL
    }
  },
  actions: {
    /* get CardSite 站点数据 */
    async getCardSite(params) {  /* get CardSite 站点数据 */
      // 1. 获取 cardsite 站点数据
      const newGetSiteParams = {
        id: params.id,
      };
      await getSiteDataToServer(newGetSiteParams, (gData) => {
        // 2. update card site data
        this.updateCardSiteData(gData)
        // 3. uadate curPageData
        this.updateCurPage(0)
      });
    },
    updateCardSiteData(data) {
      // 1. update card site data
      this.siteData = data;

      // 2. update cuePageData
      this.curPageData = this.siteData.pages[this.curPage];
    },

    /* current page */
    updateCurPage(data) {
      // 1. update curPage
      this.curPage = data;

      // 2. update cuePageData
      this.curPageData = this.siteData.pages[data];
    },

    /* common current select item */
    updateCurTarget(data) {
      this.curTarget = data;
    },

    /* update site data */
    updateCardLists(data) {
      // 1. update current Page Data
      this.curPageData = data;

      // 2. update pages
      this.siteData.pages.splice(this.curPage, 1, data);

      // Vue.set(state.siteData.pages, state.curPage, data);
    },

    /* create card site */
    createCardSite(params) {  /* 创建cardList站点 */
      // 1. 创建新的 cardSite 站点，由后端生成 id ，name
      const newCreateSiteParams = {
        id: '',
        tag: params.type,
      };
      createSiteToServer(newCreateSiteParams, (cData) => {
        // 2. 初始化站点数据
        this.initCardSiteData(cData);

        // 3. 保存站点数据
        this.saveCardSite().then(() => {
          // 4. 跳转至编辑页面
          const cardSiteId = this.siteData.id;
          router.push({ name: 'cardedit', params: { id: cardSiteId } });
        })
      });
    },
    initCardSiteData(data) {  /* 初始化cardList站点 */
      let newCardSiteData = _.cloneDeep(CardSiteDataDefault);  // 深拷贝default 初始数据
      let newAllShare = {
        ...newCardSiteData.attrs.share.allShare,
        title: data.name,
      };
      newCardSiteData = {
        ...newCardSiteData,
        id: data.id,
        attrs: {
          ...newCardSiteData.attrs,
          containerid: BUSINESS_NO_CARD + '_-_' + data.id,
          share_containerid: BUSINESS_NO_CARD + '_-_' + data.id,
          h5Type: data.tag,
          share: {
            ...newCardSiteData.attrs.share,
            allShare: newAllShare,
          },
        },
        pages: [[]],
      };
      this.siteData = newCardSiteData;
    },

    /* 拷贝站点 */
    createCopySite(params) {
      const router = useRouter()
      // 拷贝逻辑需要重新梳理
      // 1. itemid 改变
      // 2. 参数
      // console.log(params);

      // 0.
      if (!params || !params.data) return;

      // 1. 创建copy的 cardSite 站点，由后端生成 id ，name
      const newCreateSiteParams = {
        id: '',
        tag: params.type,
      };
      createSiteToServer(newCreateSiteParams, (cData) => {
        // 2. container_id
        // const container_id = BUSINESS_NO_CARD + '_-_' + cData.id;

        // 3. 初始化站点数据
        this.copyCardSiteData({ cData: cData, params: params })

        // 4. 保存站点数据
        this.saveCardSite(() => {
          // 6. 跳转至编辑页面
          const cardSiteId = this.siteData.id;
          router.push({ name: 'cardedit', params: { id: cardSiteId } });
        })
      });
    },
    copyCardSiteData({ cData, params }) {
      // 1. copy data <= params.data(old data)
      let newCardSiteData = _.cloneDeep(params.data);  // 深拷贝数据
      newCardSiteData = {
        ...newCardSiteData,
        id: cData.id,
        attrs: {
          ...newCardSiteData.attrs,
          containerid: BUSINESS_NO_CARD + '_-_' + cData.id,
          share_containerid: BUSINESS_NO_CARD + '_-_' + cData.id,
          h5Type: cData.tag,
          copy_from: params.data.id,
        },
      };

      // 2. pages
      const _copyItem = (item, oldStr, newStr) => {
        return item && {
          ..._.cloneDeep(item),
          ...(item.card_type == 2001 ? {
            card_id: item.card_id.replaceAll(oldStr, newStr),
          } : null),
          itemid: item.itemid.replace(oldStr, newStr),
        };
      };
      let newPage = newCardSiteData.pages && newCardSiteData.pages.map((page) => {
        return page && page.map((item) => {
          if (item.card_type == 11 || item.card_type == 'JY0001') {
            return {
              ..._copyItem(item, params.data.id, cData.id),
              card_group: item.card_group && item.card_group.map((child_item) => {
                return _copyItem(child_item, params.data.id, cData.id);
              }),
            };
          }
          else if (item.card_type == 86) {
            return {
              ..._copyItem(item, params.data.id, cData.id),
              sub_cards: item.sub_cards && item.sub_cards.map((child_item) => {
                return _copyItem(child_item, params.data.id, cData.id);
              }),
            };
          }
          else {
            return _copyItem(item, params.data.id, cData.id);
          }
        });
      });
      newCardSiteData = {
        ...newCardSiteData,
        pages: newPage,
      };
      state.siteData = newCardSiteData;
    },

    /* save card site */
    async saveCardSite(params) {
      // 1. update uids / mids
      // TODO: 检查 uids / mids 是否填写？
      this.updateUidsAndMids()

      // 2. 清空 mblog
      this.clearCardMblog()

      // 3. 保存站点数据
      // console.log('state.siteData: ', state.siteData);
      const newSaveSiteDataParams = {
        ...this.siteData,
      };
      await saveSiteDatasToServer(newSaveSiteDataParams, (sData) => {
        // console.log('sData: ', sData);

        // 4. callback
        if (params && params.callback) params.callback(sData);
      });
    },
    updateUidsAndMids() {
      // 1. 收集 uids / mids
      let arrUids = [];
      let arrMids = [];

      // 2. handlerUidsAndMids
      const handlerUidsAndMids = (card) => {
        if (card.card_type == 59) {
          handlerUidsAndMids(card.left_element);
          handlerUidsAndMids(card.right_element);
        }
        else if (card.card_type == 88) {
          handlerUidsAndMids(card.left_element);
          handlerUidsAndMids(card.right_element);
        }
        else {
          if (typeof card.Idx_uid == 'string' && card.Idx_uid != '' && arrUids.indexOf(card.Idx_uid) == -1)
            arrUids.push(card.Idx_uid);
          if (typeof card.Idx_mid == 'string' && card.Idx_mid != '' && arrMids.indexOf(card.Idx_mid) == -1)
            arrMids.push(card.Idx_mid);
        }
      };

      // 3. 循环遍历
      this.siteData.pages && this.siteData.pages.forEach((cardLists) => {
        cardLists.forEach((card) => {
          handlerUidsAndMids(card);

          if (card.card_type == 11) {
            card.card_group && card.card_group.forEach((cardGroupChild) => {
              handlerUidsAndMids(cardGroupChild);
            });
          }
          else if (card.card_type == 'JY0001') {
            card.card_group && card.card_group.forEach((cardGroupChild) => {
              if (cardGroupChild && cardGroupChild['obj_52'] && cardGroupChild['obj_52']['item'])
                handlerUidsAndMids(cardGroupChild['obj_52']['item']);
            });
          }
          else if (card.card_type == 206) {
            card.items && card.items.forEach((item) => {
              handlerUidsAndMids(item);
            })
          }
        });
      });

      // 2. update this.siteData.uids / this.siteData.mids
      this.siteData.uids = arrUids;
      this.siteData.mids = arrMids;
    },
    clearCardMblog() {
      // 0. handlerClearCardMblog
      const handlerClearCardMblog = (card) => {
        if (card.card_type == 9) card.mblog = {};
        if (card.card_type == 59) {
          card.left_element.mblog = {};
          card.right_element.mblog = {};
        }
        if (card.card_type == 81) card.mblog = {};
        if (card.card_type == 88) {
          card.left_element.mblog = {};
          card.right_element.mblog = {};
        }
        if (card.card_type == 124) {
          card.lists && card.lists.length > 0 && card.lists.map((child_item) => {
            child_item.statuses = [];
            return child_item;
          })
        }
      };

      // 1. 清空 mblog
      this.siteData.pages && this.siteData.pages.map((cardLists) => {
        return cardLists.map((card) => {
          handlerClearCardMblog(card);

          if (card.card_type == 11) {
            card.card_group && card.card_group.forEach((cardGroupChild) => {
              handlerClearCardMblog(cardGroupChild);

              return cardGroupChild;
            });
          }

          return card;
        });
      });
    },

    /* update Card Page Info */
    updateCardPageInfo(data) {
      this.siteData.attrs = data;
    },

    /* update Pages */
    updatePages(data) {
      this.siteData.pages = data;
    },

    /* on/off line */
    async onlineSite(params) {  /* status: online 2-下线，1-上线 */
      // 1. 上/下线
      const newOnlineParams = {
        site_id: params.id,
        online: params.status,
      };
      await online(newOnlineParams, () => {
        // 2. update card site preshow data
        this.updateCardSitePreshowData({
          ...this.sitePreshowData,
          status: params.status,
        });
      });
    },

    /* handler for Add Page */
    handler4AddPage() {  // 添加页
      this.siteData.pages.push([]);
    },

    /* handler for Add Panel */
    handler4AddPanel() {  // 添加弹层
      if (!this.siteData.panels) this.siteData.panels = [];
      this.siteData.panels.push([]);
    },

    /* update Panels */
    updatePanels(data) {
      if (!this.siteData.panels) this.siteData.panels = [];
      this.siteData.panels = data;
    },
    updatePanelLists({data, index}) {
      this.siteData.panels.splice(index, 1, data);
    },

    /* beforeUnmount */
    clear(data) {
      // clear card Components
      this.siteData = {
        id: '',
        attrs: {
          desc: '',
        },
        pages: [],
        controls: [],
        uids: [],
        mids: [],
      };
      this.sitePreshowData = {
        status: '',
      };
      this.curTarget = {
        itemId: '',
        parentId: '',
      };
      this.mgSitePreview = {
        isActive: false,
      };
      this.curPage = 0;
      this.curPageData = [];
      this.curLayoutType = 'PAGE';
    },

    /* get Card Site Preshow */
    async getCardSitePreshow(params) {  /* get CardSite preshow 站点预览数据 */
      // 1. 获取 cardsite preshow 站点预览数据
      const newGetSitePreshowParams = {
        site_id: params.id,
      };
      await getTempPreviewUrl(newGetSitePreshowParams, (gData) => {
        // 2. update card site preshow data
        this.updateCardSitePreshowData(gData)

        // 3. update card site data qrcode
        if (!this.siteData.attrs.qrcode || this.siteData.attrs.qrcode == '') {
          this.updateCardSiteData({
            ...this.siteData,
            attrs: {
              ...this.siteData.attrs,
              qrcode: gData.qrcode,
            },
          })
        }
        // console.log('getTempPreviewUrl gData: ', gData);
      });
    },

    /* 预览 */
    updateMgSitePreview(params) {
      this.mgSitePreview = params;
    },

    /* generate Qrcode */
    recoverSiteQrcode(params) {
      const newParams = {
        site_id: params.site_id,
      };
      recoverSiteQrcode(newParams, (data) => {
        // online 2-下线，1-上线
        let qrData = data[this.siteData.id]
        this.sitePreshowData.qrcode = this.sitePreshowData.status == 1 ? qrData.online : qrData.tmp

        // callback
        if (params.callback) params.callback(data);
      })
    },

    /* get CardSite preshow 站点预览数据 */
    async getCardSitePreshow4Qrcode(params) {
      // 1. 获取 cardsite preshow 站点预览数据
      const newGetSitePreshowParams = {
        site_id: params.id,
      };
      await getTempPreviewUrl(newGetSitePreshowParams, (gData) => {
        // 2. update card site preshow data
        this.updateCardSitePreshowData(gData)

        // 3. update card site data qrcode
        this.updateCardSiteData({
          ...this.siteData,
          attrs: {
            ...this.siteData.attrs,
            qrcode: gData.qrcode,
          },
        })

        // console.log('getTempPreviewUrl gData: ', gData);
      });
    },

    /* update sitePreshowData */
    updateCardSitePreshowData( data) {
      this.sitePreshowData = data;
    },
  },
})

if (import.meta.hot) {
  import.meta.hot!.accept(acceptHMRUpdate(useWebCardCompStore, import.meta.hot))
}
